package com.cyf.plc.data.repository

import com.cyf.plc.bean.*
import com.cyf.plc.data.remote.CityService
import com.cyf.plc.data.remote.Pm25Service
import com.cyf.plc.data.remote.Pm25Service.Companion.TOKEN
import com.cyf.plc.data.remote.WeatherService
import com.cyf.plc.data.remote.WeatherService.Companion.API_KEY
import com.cyf.plc.util.State
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import retrofit2.Response
import javax.inject.Inject
import javax.inject.Singleton

@ExperimentalCoroutinesApi
@Singleton
class NetRepository @Inject constructor(
    val cityService: CityService,
    val weatherService: WeatherService,
    val pm25Service: Pm25Service
) {


    /**
     * 请求PM2.5
     */
    fun getPm25(city: String?): Flow<State<String>> {

        return object : NetworkBoundRepository<String>() {

            override suspend fun fetchFromRemote(): Response<String> =
                pm25Service.getPm25(city, TOKEN)

        }.asFlow().flowOn(Dispatchers.IO)
    }

    /**
     * 请求city
     */
    fun getCity(): Flow<State<String>> {

        return object : NetworkBoundRepository<String>() {

            override suspend fun fetchFromRemote(): Response<String> = cityService.getCity("utf-8")

        }.asFlow().flowOn(Dispatchers.IO)
    }

    /**
     * 请求key
     */
    fun getKey(ip: String): Flow<State<WeatherKey>> {

        return object : NetworkBoundRepository<WeatherKey>() {

            override suspend fun fetchFromRemote(): Response<WeatherKey> =
                weatherService.getKey(ip, API_KEY)

        }.asFlow().flowOn(Dispatchers.IO)
    }

    /**
     * 请求天气
     */
    fun getWeather(key: String?, languageRange: String): Flow<State<List<WeatherStatus>>> {

        return object : NetworkBoundRepository<List<WeatherStatus>>() {

            override suspend fun fetchFromRemote(): Response<List<WeatherStatus>> =
                weatherService.getWeather(
                    key,
                    true,
                    API_KEY,
                    languageRange
                )

        }.asFlow().flowOn(Dispatchers.IO)
    }

    /**
     * 请求天气
     */
    fun getWeather(cityBean: CityBean?): Flow<State<WeatherResponse>> {

        return object : NetworkBoundRepository<WeatherResponse>() {

            override suspend fun fetchFromRemote(): Response<WeatherResponse> = weatherService.getWeather(cityBean)
        }.asFlow().flowOn(Dispatchers.IO)
    }

    /**
     * 从云获取配置列表
     */
    fun getYunConfig(deviceId:String): Flow<State<FloorRoomResponse>>{
        return object : NetworkBoundRepository<FloorRoomResponse>() {
            override suspend fun fetchFromRemote(): Response<FloorRoomResponse> = weatherService.getFloorRoom(DeviceBean(deviceId))
        }.asFlow().flowOn(Dispatchers.IO)
    }
}